package cn.yanghan.userdetails;

import cn.yanghan.domain.LoginUser;
import cn.yanghan.domain.Permission;
import cn.yanghan.mapper.PermissionMapper;
import cn.yanghan.service.ILoginUserService;
import cn.yanghan.utils.exception.Assert;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
    
    @Autowired
    private ILoginUserService loginUserService;

    @Autowired
    private PermissionMapper permissionMapper;
    /**
     * Security底层会调用该方法来加载数据库中的用户信息
     * 重写loadUserByUsername方法
     * @param
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.根据用户名查询login
        Assert.assertNotEmpty(username,"用户名不能为空");
        Wrapper<LoginUser> wrapper= new EntityWrapper<>();
        wrapper.eq("username",username);
        LoginUser loginUser = loginUserService.selectOne(wrapper);
        if(loginUser==null){
            throw new NullPointerException("用户没找到");
        }
        //2.查询用户权限
        List<Permission> permissions =  permissionMapper.selectByUserId(loginUser.getId());

        //map映射
        List<SimpleGrantedAuthority> authorities = permissions.stream()
                .map(permission -> new SimpleGrantedAuthority(permission.getSn()))
                .collect(Collectors.toList());

        //怎样拿到机构？1.调用fegin ，管理中心查询机构  2.数据库冗余字段
        String password = loginUser.getPassword();
        loginUser.setPassword(null);
        loginUser.setPassword(null);
        String login = JSON.toJSONString(loginUser);

        return new User(
                login, //用户名
                password, //密码
                true, //账号启用
                true, //账户是否过期
                true, //密码是否过期
                true ,//账户是否锁定
                authorities); //用户权限
    }
}
